package com.dqyy.order.task;

import com.dqyy.order.service.EmailService;
import com.dqyy.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class OrderSummaryEmailTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private EmailService emailService;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${order.summary.email.to}")
    private String toEmail;

    /**
     * 每天18:00发送订单汇总邮件
     */
    @Scheduled(cron = "0 0 18 * * ?")
    // 每5秒执行一次
//    @Scheduled( cron = "0/30 * * * * ?")

    public void sendOrderSummaryEmail() {
        log.info("开始执行订单汇总邮件发送任务");
        try {
            // 获取订单汇总信息
            Map<String, Object> summary = orderService.getOrderSummary();
            
            // 构建邮件内容
            String subject = "每日订单汇总 - " + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            StringBuilder content = new StringBuilder();
            content.append("<h2>每日订单汇总</h2>");
            content.append("<p>统计时间：").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("</p>");
            content.append("<p>总订单数：").append(summary.get("totalOrders")).append("</p>");
            content.append("<p>总销售额：").append(summary.get("totalSales")).append(" 元</p>");
            content.append("<p>今日订单数：").append(summary.get("todayOrders")).append("</p>");
            
            // 发送HTML格式邮件
            emailService.sendHtmlEmail(toEmail, subject, content.toString());
            log.info("订单汇总邮件发送成功");
        } catch (Exception e) {
            log.error("订单汇总邮件发送失败", e);
        }
    }
} 